// 弹幕存储服务
export interface StoredDanmu {
    id: string;
    text: string;
    timestamp: number; // 视频时间戳（秒）
    color: string;
    createdAt: number; // 创建时间
}

class DanmuStorageService {
    private storageKey = 'danmu_history';
    private maxStorageSize = 1000; // 最大存储弹幕数量

    // 保存弹幕到本地存储
    saveDanmu(danmu: Omit<StoredDanmu, 'id' | 'createdAt'>): void {
        try {
            const storedDanmus = this.getAllDanmus();
            const newDanmu: StoredDanmu = {
                ...danmu,
                id: `stored_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                createdAt: Date.now()
            };

            storedDanmus.push(newDanmu);

            // 按时间戳排序
            storedDanmus.sort((a, b) => a.timestamp - b.timestamp);

            // 限制存储数量，保留最新的弹幕
            if (storedDanmus.length > this.maxStorageSize) {
                storedDanmus.splice(0, storedDanmus.length - this.maxStorageSize);
            }

            localStorage.setItem(this.storageKey, JSON.stringify(storedDanmus));
            console.log('弹幕已保存:', newDanmu);
        } catch (error) {
            console.error('保存弹幕失败:', error);
        }
    }

    // 获取所有存储的弹幕
    getAllDanmus(): StoredDanmu[] {
        try {
            const stored = localStorage.getItem(this.storageKey);
            return stored ? JSON.parse(stored) : [];
        } catch (error) {
            console.error('读取弹幕失败:', error);
            return [];
        }
    }

    // 根据时间范围获取弹幕
    getDanmusByTimeRange(startTime: number, endTime: number): StoredDanmu[] {
        const allDanmus = this.getAllDanmus();
        return allDanmus.filter(danmu =>
            danmu.timestamp >= startTime && danmu.timestamp <= endTime
        );
    }

    // 获取指定时间点的弹幕
    getDanmusAtTime(time: number, tolerance: number = 0.5): StoredDanmu[] {
        const allDanmus = this.getAllDanmus();
        return allDanmus.filter(danmu =>
            Math.abs(danmu.timestamp - time) <= tolerance
        );
    }

    // 删除指定弹幕
    deleteDanmu(id: string): void {
        try {
            const storedDanmus = this.getAllDanmus();
            const filteredDanmus = storedDanmus.filter(danmu => danmu.id !== id);
            localStorage.setItem(this.storageKey, JSON.stringify(filteredDanmus));
            console.log('弹幕已删除:', id);
        } catch (error) {
            console.error('删除弹幕失败:', error);
        }
    }

    // 清空所有弹幕
    clearAllDanmus(): void {
        try {
            localStorage.removeItem(this.storageKey);
            console.log('所有弹幕已清空');
        } catch (error) {
            console.error('清空弹幕失败:', error);
        }
    }

    // 获取弹幕统计信息
    getStats(): { total: number; timeRange: { min: number; max: number } } {
        const allDanmus = this.getAllDanmus();
        if (allDanmus.length === 0) {
            return { total: 0, timeRange: { min: 0, max: 0 } };
        }

        const timestamps = allDanmus.map(danmu => danmu.timestamp);
        return {
            total: allDanmus.length,
            timeRange: {
                min: Math.min(...timestamps),
                max: Math.max(...timestamps)
            }
        };
    }

    // 导出弹幕数据
    exportDanmus(): string {
        const allDanmus = this.getAllDanmus();
        return JSON.stringify(allDanmus, null, 2);
    }

    // 导入弹幕数据
    importDanmus(data: string): boolean {
        try {
            const importedDanmus: StoredDanmu[] = JSON.parse(data);
            if (Array.isArray(importedDanmus)) {
                localStorage.setItem(this.storageKey, JSON.stringify(importedDanmus));
                console.log('弹幕数据导入成功');
                return true;
            }
            return false;
        } catch (error) {
            console.error('导入弹幕数据失败:', error);
            return false;
        }
    }
}

// 创建单例实例
export const danmuStorageService = new DanmuStorageService();
